package com.uphone.kingmall.utils.version;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.Gravity;

import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.ToastUtils;
import com.china.zhuoyue.BuildConfig;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.listener.onDownloadFileListener;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.OkGoUtils;

import java.io.File;

/**
 * 版本信息相关工具类
 *
 * @author cbh
 */
@SuppressWarnings("WeakerAccess")
public class VersionUtil {

    /**
     * 安装apk权限请求吗
     */
    public static final int REQUEST_PERMISSION_INSTALL = 300;

    /**
     * 弹出版本提示对话框
     */
    public static void showAlertDialog(final BaseActivity activity, final VersionBean.VersionInfo bean) {
        DialogUtil.showMsgDialog(activity, 0, "版本更新", bean.description.replace("|", "\n"),
                bean.state == 1 ? "" : "取消", "立即更新", Gravity.START | Gravity.CENTER_VERTICAL, false,
                new DialogUtil.OnConfirmButtonClick() {
                    @Override
                    public void onConfirmButtonClick(Dialog dialog, String inputText) {
                        doUpdate(bean, true, activity);
                        dialog.cancel();
                    }
                }).setCancelable(false);
    }

    /**
     * Android8.0安装apk权限
     */
    public static boolean checkHasPermission(BaseActivity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean isHasPermission = activity.getPackageManager().canRequestPackageInstalls();
            if (isHasPermission) {
                return true;
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                activity.startActivityForResult(intent, REQUEST_PERMISSION_INSTALL);
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * 执行更新操作
     *
     * @param isShowDownDialog 是否弹出下载对话框
     */
    public static void doUpdate(final VersionBean.VersionInfo bean, final boolean isShowDownDialog, final BaseActivity activity) {
        final File apkFile = getApkFile(bean.version);
        if (apkFile.exists()) {
            installApk(apkFile, activity);
        } else {
            Dialog progressDialog = null;
            if (isShowDownDialog) {
                progressDialog = DialogUtil.showLoadingDialog(activity, "正在下载中");
                progressDialog.setCancelable(false);
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();
            } else {
                ToastUtils.showShort("正在后台下载");
            }
            final Dialog finalProgressDialog = progressDialog;
            OkGoUtils.downloadFile(bean.url, activity, getApkFolder().getPath(),
                    bean.version + ".apk", new onDownloadFileListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onDownloadProgress(Progress progress) {
                }

                @Override
                public void onSuccess(Response<File> response) {
                    onDownloadComplete(isShowDownDialog, finalProgressDialog, bean, activity);
                }

                @Override
                public void onError(Response<File> response) {

                }

                @Override
                public void onFinish() {

                }
            });
        }
    }

    /**
     * 下载完成
     */
    private static void onDownloadComplete(final boolean isShowDownDialog, final Dialog finalProgressDialog,
                                           final VersionBean.VersionInfo bean, final BaseActivity activity) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (isShowDownDialog && finalProgressDialog != null) {
                    finalProgressDialog.cancel();
                }
                //递归调用,因为apk文件已经存在,所以会走安装提示逻辑
                doUpdate(bean, isShowDownDialog, activity);
            }
        });
    }

    /**
     * 获取存放apk文件的文件夹
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    private static File getApkFolder() {
        File apkFolder = new File(MyApplication.mContext.getCacheDir(), "apk");
        if (!apkFolder.exists()) {
            apkFolder.mkdirs();
        }
        return apkFolder;
    }

    /**
     * 获取apk文件
     */
    public static File getApkFile(String versionName) {
        return new File(getApkFolder(), versionName + ".apk");
    }

    /**
     * 安装apk文件
     */
    public static void installApk(File file, BaseActivity mActivity) {
        if (!checkHasPermission(mActivity)) {
            return;
        }
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String type = "application/vnd.android.package-archive";
        Uri uri;
        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(mActivity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".myFileProvider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        installIntent.setDataAndType(uri, type);
        mActivity.startActivity(installIntent);
    }


    /**
     * 获取App版本号
     */
    public static String getAppVersion() {
        String localVersion = "";
        try {
            PackageInfo packageInfo = MyApplication.mContext.getPackageManager()
                    .getPackageInfo(MyApplication.mContext.getPackageName(), 0);
            localVersion = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

}
